package baiqitun.stupro.security.service.impl;

import baiqitun.stupro.common.exception.enums.support.ExistedExceptionEnum;
import baiqitun.stupro.common.exception.support.ExistedException;
import baiqitun.stupro.security.entity.SysDepart;
import baiqitun.stupro.security.entity.SysDepartUser;
import baiqitun.stupro.security.entity.SysUser;
import baiqitun.stupro.security.service.SysDepartService;
import baiqitun.stupro.security.service.SysDepartUserService;
import baiqitun.stupro.security.service.SysDepartUserRoleService;
import baiqitun.stupro.security.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

/**
 * @author kedaji
 */
@Service
public class SysDepartUserRoleServiceImpl implements SysDepartUserRoleService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysDepartUserService sysDepartUserService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAdministratorToRootDepart(@Validated() SysUser administrator, String departId) {

        try{
            sysUserRoleService.saveAdministrator(administrator);
        } catch (DuplicateKeyException e){
            throw new ExistedException(ExistedExceptionEnum.DEPART_EXISTED).put(SysDepart.class,"id", departId);
        }
        SysDepartUser relation = new SysDepartUser();
        relation.setUserId(administrator.getId()).setDepartId(departId).setCreateBy(administrator.getCreateBy());
        sysDepartUserService.save(relation);
    }
}
